package com.sanri.tools.modules.mock.l7.http.service.interceptors.impl;


import com.sanri.tools.modules.mock.l7.http.service.dtos.ResponseConfig;
import com.sanri.tools.modules.mock.l7.http.service.interceptors.IntermediateData;
import com.sanri.tools.modules.mock.l7.http.service.interceptors.ResponseInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
@Order(2000)
public class EncryptInterceptor implements ResponseInterceptor {
    @Override
    public boolean match(HttpServletRequest request) {
        final String platform = request.getParameter("platform");
        if (StringUtils.isNotBlank(platform)){
            // 如果请求中传了 platform 进行加密
            return true;
        }
        return false;
    }

    @Override
    public void interceptor(ResponseConfig responseConfig, IntermediateData intermediateData, Chain chain) {
        log.info("加密拦截器执行 aes");
        final ResponseConfig.ResponseDetail responseDetail = responseConfig.getResponseDetail();
        final String body = responseDetail.getBody();

        log.info("加密后内容: {}", body != null ? Base64.encodeBase64(body.getBytes()) : null);

        chain.interceptor(responseConfig,intermediateData);
    }
}
